package sdufe.lele.service;


import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Repository;
import sdufe.lele.dao.FinancialMapper;
import sdufe.lele.model.Financial2user;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.HashMap;
import java.util.List;

@Repository
public class ScheduledService {

    @Resource
    private FinancialMapper financialMapper;

    @Scheduled(cron = "0 30 23 * * *")
    public void scheduled() {

        List<Financial2user> financial2userList = financialMapper.selectVaild();
        HashMap<Integer, Double> ratemap = new HashMap<>();
        BigDecimal current ;
        BigDecimal dec_100 = new BigDecimal(100); //利率为百分数，处以100得到实际值

        BigDecimal dec_360 = new BigDecimal(360); //按天计算利息，利率为年化收益率，处以360得到实际值

        for (Financial2user fin : financial2userList) {

            current = fin.getCurrentbalance();

            //理财产品如果在map里，就不用重复查询
            if (ratemap.containsKey(fin.getFinancialid())) {

                double rate = ratemap.get(fin.getFinancialid());

                BigDecimal interest = fin.getBalance().multiply(new BigDecimal(rate))
                        .divide(dec_100,2,RoundingMode.HALF_EVEN)
                        .divide(dec_360,2,RoundingMode.HALF_EVEN); //初始利息;

                financialMapper.updataCurrentBalance(fin.getFuid(),interest.add(current));

            }else {
                //获得当前理财产品利率
                Double rate = financialMapper.selectFinancialById(fin.getFinancialid()).getFinancialrate();

                BigDecimal interest = fin.getBalance().multiply(new BigDecimal(rate))
                        .divide(dec_100,2,RoundingMode.HALF_EVEN)
                        .divide(dec_360,2,RoundingMode.HALF_EVEN); //初始利息;
                financialMapper.updataCurrentBalance(fin.getFuid(),interest.add(current) );

                ratemap.put(fin.getFinancialid(),rate);
            }

        }

    }


}
